# LocalStack Resource Provider Scaffolding v2
from __future__ import annotations

import json
from pathlib import Path
from typing import Optional, TypedDict

import localstack.services.cloudformation.provider_utils as util
from localstack.services.cloudformation.resource_provider import (
    OperationStatus,
    ProgressEvent,
    ResourceProvider,
    ResourceRequest,
)


class ResourceGroupsGroupProperties(TypedDict):
    Name: Optional[str]
    Arn: Optional[str]
    Configuration: Optional[list[ConfigurationItem]]
    Description: Optional[str]
    ResourceQuery: Optional[ResourceQuery]
    Resources: Optional[list[str]]
    Tags: Optional[list[Tag]]


class TagFilter(TypedDict):
    Key: Optional[str]
    Values: Optional[list[str]]


class Query(TypedDict):
    ResourceTypeFilters: Optional[list[str]]
    StackIdentifier: Optional[str]
    TagFilters: Optional[list[TagFilter]]


class ResourceQuery(TypedDict):
    Query: Optional[Query]
    Type: Optional[str]


class Tag(TypedDict):
    Key: Optional[str]
    Value: Optional[str]


class ConfigurationParameter(TypedDict):
    Name: Optional[str]
    Values: Optional[list[str]]


class ConfigurationItem(TypedDict):
    Parameters: Optional[list[ConfigurationParameter]]
    Type: Optional[str]


REPEATED_INVOCATION = "repeated_invocation"


class ResourceGroupsGroupProvider(ResourceProvider[ResourceGroupsGroupProperties]):
    TYPE = "AWS::ResourceGroups::Group"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

    def create(
        self,
        request: ResourceRequest[ResourceGroupsGroupProperties],
    ) -> ProgressEvent[ResourceGroupsGroupProperties]:
        """
        Create a new resource.

        Primary identifier fields:
          - /properties/Name

        Required properties:
          - Name

        Create-only properties:
          - /properties/Name

        Read-only properties:
          - /properties/Arn

        IAM permissions required:
          - resource-groups:CreateGroup
          - resource-groups:Tag
          - cloudformation:DescribeStacks
          - cloudformation:ListStackResources
          - resource-groups:ListGroupResources
          - resource-groups:GroupResources

        """
        model = request.desired_state
        client = request.aws_client_factory.resource_groups

        if not model.get("Name"):
            raise ValueError("Name is a required property")

        # Default query
        resource_query = model.get("ResourceQuery", {})
        if (
            not resource_query.get("Query")
            and resource_query.get("Type") == "CLOUDFORMATION_STACK_1_0"
        ):
            resource_query["Query"] = json.dumps(
                {"ResourceTypeFilters": ["AWS::AllSupported"], "StackIdentifier": request.stack_id}
            )

        params = util.select_attributes(
            model, ["Name", "Description", "ResourceQuery", "Configuration"]
        )

        if tags := model.get("Tags"):
            params["Tags"] = util.transform_list_to_dict(tags)

        result = client.create_group(**params)
        model["Arn"] = result["Group"]["GroupArn"]

        return ProgressEvent(status=OperationStatus.SUCCESS, resource_model=model)

    def read(
        self,
        request: ResourceRequest[ResourceGroupsGroupProperties],
    ) -> ProgressEvent[ResourceGroupsGroupProperties]:
        """
        Fetch resource information

        IAM permissions required:
          - resource-groups:GetGroup
          - resource-groups:GetGroupQuery
          - resource-groups:GetTags
          - resource-groups:GetGroupConfiguration
          - resource-groups:ListGroupResources
        """
        raise NotImplementedError

    def delete(
        self,
        request: ResourceRequest[ResourceGroupsGroupProperties],
    ) -> ProgressEvent[ResourceGroupsGroupProperties]:
        """
        Delete a resource

        IAM permissions required:
          - resource-groups:DeleteGroup
          - resource-groups:UnGroupResources
        """
        client = request.aws_client_factory.resource_groups
        client.delete_group(GroupName=request.desired_state["Name"])
        return ProgressEvent(status=OperationStatus.SUCCESS, resource_model={})

    def update(
        self,
        request: ResourceRequest[ResourceGroupsGroupProperties],
    ) -> ProgressEvent[ResourceGroupsGroupProperties]:
        """
        Update a resource

        IAM permissions required:
          - resource-groups:UpdateGroup
          - resource-groups:GetTags
          - resource-groups:GetGroupQuery
          - resource-groups:UpdateGroupQuery
          - resource-groups:Tag
          - resource-groups:Untag
          - resource-groups:PutGroupConfiguration
          - resource-groups:GetGroupConfiguration
          - resource-groups:ListGroupResources
          - resource-groups:GroupResources
          - resource-groups:UnGroupResources
        """
        raise NotImplementedError
